<template>
  <div class="edit">
    <el-container>
      <el-header class="edit-header">
        <div class="edit-left">
          <span class="edit-title">页面在线编辑器</span>
          <el-button icon="el-icon-download" size="small"> 导入 </el-button>
        </div>
        <div class="edit-right">
          <el-alert
            title="「Ctrl + S 保存更新视图」 "
            effect="dark"
            type="warning"
            :closable="false"
          />
        </div>
      </el-header>
      <el-main>
        <div ref="el" class="editor-area" />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { JSONStringify } from '@/utils'
import store from '@/store/modules/chartEdit'
export default {
  data () {
    return {
      initReadOnly: false,
      monacoEditor: null,
      content: '',
      preComment: ''
    }
  },
  mounted () {
    this.createEditor({ lineNumbers: 'on', minimap: { enabled: true } })
    this.monacoEditor.onDidChangeModelContent(() => this.content = this.monacoEditor.getValue())
    setTimeout(() => this.getDataBySession())
    // 保存按钮同步数据
    document.addEventListener('keydown', (e) => {
      if (e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
        e.preventDefault()
        this.updateSync()
      }
    })
  },
  methods: {
    // 创建实例
    createEditor (editorOption) {
      if (!this.$refs.el) return
      const javascriptModel = monaco.editor.createModel('', 'json')
      console.log(javascriptModel, 'javascriptModel')
      this.initReadOnly = !!editorOption.readOnly
      // 创建
      this.monacoEditor = monaco.editor.create(this.$refs.el, {
        model: javascriptModel,
        // 是否启用预览图
        minimap: { enabled: false },
        // 圆角
        roundedSelection: true,
        // 主题
        theme: 'vs',
        // 主键
        multiCursorModifier: 'ctrlCmd',
        // 滚动条
        scrollbar: {
          verticalScrollbarSize: 8,
          horizontalScrollbarSize: 8
        },
        // 行号
        lineNumbers: 'off',
        // tab大小
        tabSize: 2,
        //字体大小
        fontSize: 16,
        // 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
        autoIndent: 'advanced',
        // 自动布局
        automaticLayout: true,
        ...editorOption,
      })
    },
    // 更新
    updateVal (val) {
      this.$nextTick(async () => {
        this.monacoEditor?.setValue(val)
        this.initReadOnly && this.monacoEditor.updateOptions({ readOnly: false })
        await this.monacoEditor.getAction('monacoEditor.action.formatDocument')?.run()
        this.initReadOnly && this.monacoEditor.updateOptions({ readOnly: true })
      })
    },
    // 获取存储数据的信息
    getSessionStorageInfo () {
      let storageList = JSON.parse(sessionStorage.getItem('chartList'))
      const { editCanvasConfig, componentList } = storageList[0]
      store.state.editCanvasConfig = editCanvasConfig
      store.state.componentList = componentList
      return storageList[0]
    },
    // 从sessionStorage 获取数据
    getDataBySession () {
      const localStorageInfo = this.getSessionStorageInfo()
      document.title = `编辑`
      this.content = JSONStringify(localStorageInfo)
    },
    updateMonacoVal (_val) {
      const { content, preComment } = this
      const val = preComment ? `${preComment}\n${_val || content}` : _val || content
      this.updateVal(val)
    },
    // 同步更新
    async updateSync () {
      if (!window.opener) return this.$message.error('源窗口已关闭，视图同步失败！')
      try {
        await this.$confirm('是否覆盖源视图内容? 此操作不可撤!', '提示', { type: 'warning' })
        const detail = JSON.parse(this.content)
        delete detail.id
        window.opener.dispatchEvent(new CustomEvent('SaveJSON', { detail }))
        this.$message.success('正在同步内容...')
      } catch (error) { console.log(error) }
    }
  },
  watch: {
    content (val) {
      if (val !== this.monacoEditor.getValue()) {
        this.updateMonacoVal(val)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit {
  display: flex;
  flex-direction: column;
  height: 100vh;
  .edit-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .edit-title {
      font-size: 18px;
      font-weight: bold;
      margin-right: 30px;
    }
  }
  .editor-area {
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    padding: 5px;
    padding-left: 0;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0);
    height: calc(100vh - 60px);
    // @include deep() {
    //   .margin,
    //   .monaco-editor,
    //   .inputarea.ime-input {
    //     background-color: rgba(0, 0, 0, 0);
    //   }

    //   .monaco-editor-background {
    //     background-color: rgba(0, 0, 0, 0);
    //     @include fetch-bg-color('filter-color-shallow');
    //   }
    //   .margin {
    //     @include fetch-bg-color('filter-color-shallow');
    //   }
    // }
  }
}
</style>